<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="用户" prop="userId">
        <el-input
          v-model="selectedUserDisplay"
          placeholder="请选择用户"
          clearable
          readonly
          @clear="handleClearUser"
        >
          <template #suffix>
            <Icon
              icon="ep:search"
              class="cursor-pointer hover:text-primary"
              @click="openUserDialog"
            />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="拉黑原因" prop="blacklistReason">
        <el-input v-model="formData.blacklistReason" placeholder="请输入拉黑原因" />
      </el-form-item>
      <el-form-item label="拉黑详情" prop="blacklistDetail">
        <el-input v-model="formData.blacklistDetail" placeholder="请输入拉黑详情" />
      </el-form-item>
      <!-- <el-form-item label="到期时间" prop="expireTime">
        <el-date-picker
          v-model="formData.expireTime"
          type="date"
          value-format="x"
          placeholder="选择到期时间"
        />
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.MEMBER_USER_TYPE)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item label="解除时间" prop="unblockTime">
        <el-date-picker
          v-model="formData.unblockTime"
          type="date"
          value-format="x"
          placeholder="选择解除时间"
        />
      </el-form-item>
      <el-form-item label="解除原因" prop="unblockReason">
        <el-input v-model="formData.unblockReason" placeholder="请输入解除原因" />
      </el-form-item>
      <el-form-item label="解除操作人" prop="unblockOperator">
        <el-input v-model="formData.unblockOperator" placeholder="请输入解除操作人" />
      </el-form-item>
      <el-form-item label="操作人" prop="operator">
        <el-input v-model="formData.operator" placeholder="请输入操作人" />
      </el-form-item> -->
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 用户选择弹窗 -->
  <UserSelectDialog ref="userDialogRef" @confirm="handleUserConfirm" />
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { BlacklistApi, BlacklistVO } from '@/api/member/blacklist'
import UserSelectDialog from './UserSelectDialog.vue'
import type { UserVO } from '@/api/member/user'

/** 会员黑名单管理 表单 */
defineOptions({ name: 'BlacklistForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<{
  id: number | undefined
  userId: number | undefined
  nickname: string | undefined
  mobile: string | undefined
  blacklistReason: string | undefined
  blacklistDetail: string | undefined
  expireTime: Date | undefined
  status: boolean | undefined
  unblockTime: Date | undefined
  unblockReason: string | undefined
  unblockOperator: string | undefined
  operator: string | undefined
  remark: string | undefined
}>({
  id: undefined,
  userId: undefined,
  nickname: undefined,
  mobile: undefined,
  blacklistReason: undefined,
  blacklistDetail: undefined,
  expireTime: undefined,
  status: undefined,
  unblockTime: undefined,
  unblockReason: undefined,
  unblockOperator: undefined,
  operator: undefined,
  remark: undefined
})
const formRules = reactive({
  userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
  blacklistReason: [{ required: true, message: '拉黑原因不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  operator: [{ required: true, message: '操作人不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const userDialogRef = ref() // 用户选择弹窗
const selectedUserDisplay = ref('') // 选中的用户显示信息

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BlacklistApi.getBlacklist(id)
      // 设置用户显示信息
      if (formData.value.userId) {
        selectedUserDisplay.value = `${formData.value.userId} - ${formData.value.nickname || ''} - ${formData.value.mobile || ''}`
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BlacklistVO
    if (formType.value === 'create') {
      await BlacklistApi.createBlacklist(data)
      message.success(t('common.createSuccess'))
    } else {
      await BlacklistApi.updateBlacklist(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userId: undefined,
    nickname: undefined,
    mobile: undefined,
    blacklistReason: undefined,
    blacklistDetail: undefined,
    expireTime: undefined,
    status: undefined,
    unblockTime: undefined,
    unblockReason: undefined,
    unblockOperator: undefined,
    operator: undefined,
    remark: undefined
  }
  selectedUserDisplay.value = ''
  formRef.value?.resetFields()
  // 设置默认值（在 resetFields 之后设置，确保不被覆盖）
  formData.value.status = 1 as any // 默认为"生效中"状态
}

/** 打开用户选择弹窗 */
const openUserDialog = () => {
  userDialogRef.value?.open()
}

/** 用户选择确认 */
const handleUserConfirm = (user: UserVO) => {
  formData.value.userId = user.id
  formData.value.nickname = user.nickname || user.name || ''
  formData.value.mobile = user.mobile || ''
  selectedUserDisplay.value = `${user.id} - ${user.nickname || user.name || ''} - ${user.mobile || ''}`
}

/** 清空用户选择 */
const handleClearUser = () => {
  formData.value.userId = undefined
  formData.value.nickname = undefined
  formData.value.mobile = undefined
  selectedUserDisplay.value = ''
}
</script>
